import axios from 'axios'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import errorIcon from '@/assets/images/error-icon.png'

// 创建 axios 实例
const service = axios.create({
  baseURL: '', // API 基础路径，可从环境变量获取
  headers: {
    'X-Client-Type': 'PC',
  },
  timeout: 15000, // 请求超时时间
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    // console.log(userStore);
    // console.log(userStore.sign);
    // 如果有 token，添加到请求头
    if (userStore.token) {
      // config.headers.Authorization = `Bearer ${userStore.token}`
      config.headers['X-Cient-Version-Name'] = userStore.version
      config.headers['X-Channel'] = '18500'
      config.headers['X-SubChannel'] = '18502'
      config.headers['x-Token'] = userStore.sign
      config.headers['X-Uid'] = userStore.uid
      config.headers['X-Client-Type'] = 'PC'

    }
    return config
  },
  error => {
    // 请求错误处理
    console.error('请求配置错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    // 根据后端返回的状态码进行处理
    // 这里假设后端返回的数据格式为 { code: number, message: string, data: any }
    if (res.code !== 0) {
      // 处理错误情况
      if (res.code === 401) {
        // 未登录，跳转到登录页
        const userStore = useUserStore()
        userStore.logout()
        // window.location.href = '/login'
      }

      // 显示错误消息
      // ElMessage.error(res.msg || '请求失败')
      ElMessage({
        type: 'error',
        customClass: 'custom-error-message-icon',
        dangerouslyUseHTMLString: true,
        message: `<img src="${errorIcon}" alt="error-icon" style="width: 20px; height: 20px; margin-right: 4px;">${res.msg}`,
        offset: 65
      })

      return Promise.reject(new Error(res.msg || '请求失败'))
    }

    return res.data
  },
  error => {
    // 响应错误处理
    console.error('请求错误:', error)

    // 处理网络错误、超时等情况
    let errorMessage = '网络错误，请稍后重试'
    if (error.code === 'ECONNABORTED') {
      errorMessage = '请求超时，请稍后重试'
    } else if (error.response) {
      switch (error.response.status) {
        case 401:
          errorMessage = '未授权，请重新登录'
          const userStore = useUserStore()
          userStore.logout()
          // window.location.href = '/login'
          break
        case 403:
          errorMessage = '拒绝访问'
          break
        case 404:
          errorMessage = '请求地址不存在'
          break
        case 500:
          errorMessage = '服务器内部错误'
          break
        default:
          errorMessage = error.response.data?.msg || '请求失败'
      }
    }

    // 显示错误消息
    ElMessage.error(errorMessage)
    return Promise.reject(error)
  }
)

// 导出常用的请求方法
export const request = {
  get: (url, params = {}, config = {}) => service.get(url, { params, ...config }),
  post: (url, data = {}, config = {}) => service.post(url, data, config),
  put: (url, data = {}, config = {}) => service.put(url, data, config),
  delete: (url, params = {}, config = {}) => service.delete(url, { params, ...config }),
  upload: (url, file, config = {}) => {
    const formData = new FormData()
    formData.append('file', file)
    return service.post(url, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      ...config
    })
  }
}

export default service